import React, { Component } from 'react';
import {
	StyleSheet, Text, FlatList, ActivityIndicator,
	PixelRatio, View, Image, TouchableOpacity
} from "react-native";
import { style } from '../../theme/style.js';
import { PageStatusIndex } from '../../component/page-status/PageStatusIndex';
import { Common } from '../../component/common/Common.js';
import { GLOBAL } from '../../config/global';
import MessageService from './_common/service.js';
import { HeadTab } from '../../components/common/headTab.js';
import { SwipeableItem } from './_component/swipeableItem.js';

const scale = GLOBAL.SCALE;
const ENUMSDATA = [
	{ bizType: 0, title: '公告' },
	{ bizType: 1, title: '销售申请' },
	{ bizType: 2, title: '采购申请' },
	{ bizType: 3, title: '企业通知' },
]

let pageNo = 1;//当前第几页

export class MessageListPage extends Component {

	static navigationOptions = ({ navigation }) => {
		let { bizType, navigatePress, goBack, redMessageAll } = navigation.state.params
		let getTitle = bizType;
		ENUMSDATA.forEach(element => {
			if (element.bizType == getTitle) getTitle = element.title;
		});
		return {
			headerTitle: (
				<View style={styles.TitleBox}>
					<TouchableOpacity activeOpacity={1} style={styles.TitleOut} onPress={() => { navigatePress && navigatePress() }}>
						<Text style={styles.TitleText}>{navigation.state.params.headTitle || getTitle}</Text>
						<Image style={{ marginLeft: 3 * scale }} source={require('../../imgs/Group.png')} />
					</TouchableOpacity>
				</View>
			),
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { goBack && goBack() }} color='#fff' />,
			headerRight: (navigation.state.params.onoffAll == 1 ? <Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../imgs/goBackEmpty.png')} /> : (<Text onPress={() => { redMessageAll && redMessageAll() }} style={styles.topRight}>全部已读</Text>)),
			headerStyle: {
				elevation: 0,
				backgroundColor: style.color.themeColor,
				borderBottomWidth: 0
			},
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};


	constructor(props) {
		super(props);
		let { corpId } = props.navigation.state.params || {};
		this.state = {
			_isLoad: false,  // 下拉涮新的 图标
			modalVisible: false, //  顶部下拉
			loaded: true, // 判断是否加载完成
			listData: [],
			content: '',
			createTime: '',
			totalPage: 0,  //总页数
			topLoading: true,
			footOnoff: true,
			allList: 0,
			nowList: 0,
			currentlyOpenSwipeable: null,
			isSwiping: false,
			messageType: props.navigation.state.params.bizType || 0,
			tabIndex: 0,
			corpId
		};
	}

	async	componentWillMount () {
		this.props.navigation.setParams({
			navigatePress: this._navigatePress,
			onoffAll: 0,
		});
		this.setState({
			totalPage: 1
		});
		pageNo = 1;
		await this._getData(pageNo, true);
	}
	componentDidMount () {
		this.props.navigation.setParams({
			navigatePress: this._navigatePress,
			goBack: this._goBack,
			redMessageAll: this._redMessageAll
		});
	}

	_redMessageAll = async () => {
		let { messageType } = this.state;
		let params = {
			bizType: messageType
		}
		let res = await MessageService.readMessageAll(params);
		if (res) {
			this._getData(pageNo, true);
		}
	}

	_navigatePress = () => {
		this._showVisible();
	}

	_goBack = () => {
		this.props.navigation.state.params.callBack();
		this.props.navigation.goBack();
	}

	//返回值
	_resPonseVal = (params, resVal) => {
		reset = '';
		ENUMSDATA.forEach(element => {
			if (element.bizType == params) reset = element[resVal];
		});
		return reset;
	}

	_showVisible = () => {
		if (this.state.modalVisible) {
			this.setState({
				modalVisible: false
			})
		} else {
			this.setState({
				modalVisible: true
			})
		}
	}

	_itemFn = (sendObj) => {
		this._showVisible();
		this.setState({
			messageType: sendObj.index
		}, () => {
			let { messageType } = this.state;
			pageNo = 1;
			this._getData(pageNo, true);
			this.props.navigation.setParams({
				headTitle: this._resPonseVal(messageType, 'title')
			})
		});
	}

	_modal () {
		let { messageType } = this.state;
		return (
			/* 头部弹框 */
			<Common data={ENUMSDATA} itemFn={this._itemFn} imgIndex={messageType} allClick={this._showVisible} type="selectModal" />
		)
	}

	_tabClick = (index) => {
		this.setState({
			tabIndex: index,
			isRead: index
		}, () => {
			this.props.navigation.setParams({
				onoffAll: index,
			});
			pageNo = 1;
			this._getData(pageNo, true);
		})
	}

	render () {
		let { allList, nowList, tabIndex } = this.state;
		let tabData = [
			{ title: '未读' },
			{ title: '已读' }
		]
		if (this.state.loaded) {
			//数据加载未完成
			return (
				<View style={styles.container}>
					<HeadTab data={tabData} initIndex={tabIndex} tabClick={this._tabClick} />
					<PageStatusIndex status="loading" />
				</View>
			)

		} else {
			if (this.state.listData.length) {
				const customerView = this._renderData();
				return (
					<View style={styles.container}>
						<HeadTab data={tabData} initIndex={tabIndex} tabClick={this._tabClick} />
						<View style={styles.listBox}>
							{customerView}
						</View>
						{this.state.modalVisible ? this._modal() : null}
						<View style={styles.nowBottom}>
							<Text style={styles.nowBottomText}>当前共<Text style={styles.themColor}>{allList}</Text>条消息，已加载<Text style={styles.themColor}>{nowList}</Text>条</Text>
						</View>
					</View>
				);
			} else {
				//查询结果为空时
				return (
					<View style={{ flex: 1, backgroundColor: style.color.white }}>
						<HeadTab data={tabData} initIndex={tabIndex} tabClick={this._tabClick} />
						<PageStatusIndex status="empty" emptyText={'暂无消息'} emptyImgSource={require('../../imgs/global/messageEmpty.png')} />
						{this.state.modalVisible ? this._modal() : null}
					</View>
				);
			}
		}
	}

	_getData = async (pageNo, refreshOff) => {
		let { messageType, isRead, corpId } = this.state;
		let requestObj = {
			bizType: messageType,
			pageNo,
			pageSize: 15,
			isRead: isRead || 0,   // 0 未读  1 已读
			corpId
		};

		if (refreshOff) {
			this.setState({
				_isLoad: true,
				loaded: true
			});
		}
		const responseData = await MessageService.getListData(requestObj);
		this.setState({
			allList: responseData.recordCount
		});
		if (refreshOff) {  // 下拉刷新
			if (responseData.rows.length) {
				this.setState({
					loaded: false,  // 初始化一次
					_isLoad: false,
					listData: responseData.rows,
					totalPage: responseData.totalPage,
					nowList: responseData.rows.length
				});
			} else {  //没数据
				this.setState({
					loaded: false,
					_isLoad: false,
					listData: responseData.rows,
				});
			}
		} else { // 上拉加载
			this.setState({
				listData: this.state.listData.concat(responseData.rows),
				footOnoff: false,
				nowList: this.state.nowList + responseData.rows.length
			});
		}
	}

	_handleScroll () {
		const { currentlyOpenSwipeable } = this.state;

		if (currentlyOpenSwipeable) {
			currentlyOpenSwipeable.recenter();
		}
	};

	/* 渲染列表 */
	_renderData () {
		return (
			<FlatList
				data={this.state.listData}
				extraData={this.state}
				renderItem={this._renderItemView}
				refreshing={this.state._isLoad}
				onRefresh={this._isLoadRefresh.bind(this)}
				onEndReachedThreshold={0.5}
				ListFooterComponent={this._renderFooter.bind(this)}
				onEndReached={this._onEndReached.bind(this)}
			/>
		);
	}
	//点击删除
	_removePress = async (data) => {
		const { noticeNo } = data;
		let sendData = { 'ids': [noticeNo] };
		let { listData, nowList, allList } = this.state;
		const deleteInfo = await MessageService.deleteMessage(sendData);
		if (deleteInfo) {
			let newArr = [];
			for (let i = 0; i < listData.length; i++) {
				if (listData[i].noticeNo != noticeNo) {
					newArr.push(listData[i]);
				}
			}
			this.setState({
				listData: newArr,
				nowList: --nowList,
				allList: --allList
			});
		}

	}

	// 下拉更新函数
	async _isLoadRefresh () {
		pageNo = 1;
		await this._getData(pageNo, true);
	}

	// 上拉更新函数
	_onEndReached () {
		if (pageNo < this.state.totalPage) {
			pageNo++;
			this._getData(pageNo);
		} else {
			this.setState({
				footOnoff: false
			});
		}
	}

	/*for FlatList的底部*/
	_renderFooter () {
		return <View>
			<ActivityIndicator
				style={this.state.footOnoff ? null : styles.disNone}
				animating={this.state.footOnoff}
				size="large"
				color="orange"
			/>
		</View>
	}


	// 跳转详情页面
	_goDetail = (noticeNo) => {
		let cunData = this.state.listData;
		let { messageType, corpId } = this.state;
		for (let i = 0; i < this.state.listData.length; i++) {
			if (this.state.listData[i].noticeNo == noticeNo) {
				cunData[i].isRead = 1;
				this.setState({
					data: cunData
				});
				break
			}
		}
		this.props.navigation.navigate('MessageDetailsPage',
			{
				noticeNo,
				corpId,
				title: this._resPonseVal(messageType, 'title'),
				callBack: () => {
					pageNo = 1;
					this._getData(pageNo, true);
				}
			});
	}



	//返回itemView
	_renderItemView = (customer) => {
		let { messageType } = this.state;
		let imgArr = [
			require('../../imgs/notice.png'),
			require('../../imgs/Group4.png'),
			require('../../imgs/Group5.png'),
			require('../../imgs/Group6.png'),
		]
		return (
			<SwipeableItem data={customer.item} imgObj={imgArr[messageType]} removePress={this._removePress} goDetail={this._goDetail} />
		)
	}

}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.light
	},
	listBox: {
		width: '100%',
		paddingBottom: 80 * scale
	},
	mask: {
		flex: 1,
		backgroundColor: '#000',
	},
	modalBox: {
		flex: 1,
		justifyContent: 'center',
		padding: 45 * scale,
		backgroundColor: 'rgba(0, 0, 0, 0.5)'
	},
	innerContainer: {
		borderRadius: 9 * scale,
		alignItems: 'center',
		backgroundColor: '#fff',
	},
	bombTitle: {
		alignItems: 'center',
		marginTop: 17 * scale,
		marginBottom: 14 * scale,
	},
	bombTitleText: {
		fontSize: 20 * scale,
		color: style.color.dark
	},
	bombClose: {
		height: 45 * scale,
		width: '100%',
		backgroundColor: style.color.themeColor,
		justifyContent: 'center',
		alignItems: 'center',
		borderBottomLeftRadius: 9 * scale,
		borderBottomRightRadius: 9 * scale,
	},
	bombCloseText: {
		fontSize: 18 * scale,
		color: style.color.white
	},
	bombListBox: {
		marginLeft: 30 * scale,
		marginRight: 30 * scale,
		marginBottom: 20 * scale
	},
	bombList: {
		flexDirection: 'row',
		justifyContent: 'flex-start',
		width: '100%',
		marginBottom: 7 * scale,
	},
	bombKey: {
		width: 40 * scale,
		fontSize: 12 * scale
	},
	bombVal: {
		fontSize: 12 * scale
	},
	loadedCell: {
		width: 75 * scale,
		height: 75 * scale,
		backgroundColor: 'rgba(0, 0, 0, .5)',
		borderRadius: 7,
		justifyContent: 'center',
		alignItems: 'center',
	},
	footer: {
		flexDirection: 'row',
		height: 24,
		justifyContent: 'center',
		alignItems: 'center',
		marginBottom: 10,
	},
	noMoreText: {
		color: '#999999',
		fontSize: 14 * scale,
		marginTop: 5 * scale,
		marginBottom: 5 * scale,
	},
	TitleBox: {
		flex: 1
	},
	TitleOut: {
		width: '100%',
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center'
	},
	TitleText: { color: '#fff', fontSize: 18 * scale },
	nowBottom: {
		position: 'absolute',
		bottom: 0,
		height: 40 * scale,
		width: '100%',
		backgroundColor: style.color.white,
		borderTopWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderTopColor: style.color.border,
	},
	nowBottomText: {
		textAlign: 'center',
		lineHeight: 40 * scale,
		fontSize: 12 * scale,
		color: style.color.dark
	},
	themColor: {
		color: style.color.themeColor
	},
	disNone: { height: 0, width: 0 },
	tabTop: {
		height: 40 * scale,
		backgroundColor: style.color.themeColor,
		flexDirection: 'row',
		justifyContent: 'space-around',
		alignItems: 'center'
	},
	tabBox: {
		width: '50%',
		height: 40 * scale,
		marginTop: 5 * scale,
		alignItems: 'center',
		justifyContent: 'space-between'
	},
	TabText: {
		fontSize: 14 * scale,
		color: style.color.white,
		textAlign: 'center'
	},
	topRight: {
		fontSize: 14 * scale,
		color: '#fff',
		marginRight: 10 * scale
	}
});